//
//  OilCardPayViewController.m
//  JxCarios
//
//  Created by xcq on 15/2/14.
//  Copyright (c) 2015年 xiongchuanqi. All rights reserved.
//

#import "OilCardPayViewController.h"
#import "OilCardTableViewCell.h"
#import "OilCardQueryViewController.h"
static NSString *cellIndentifire = @"OilCard";
@interface OilCardPayViewController () <UITableViewDataSource,UIAlertViewDelegate,UITableViewDelegate>
{
    BOOL keyBoradShow;
    BOOL fanhui;
}
@end

@implementation OilCardPayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    keyBoradShow = NO;
    fanhui = NO;
    [self initAbout];
    [self netRequst];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                  selector:@selector(keyboardWillShow:)
                                                      name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                  selector:@selector(keyboardWillHide:)
                                                      name:UIKeyboardWillHideNotification object:nil];
    if (fanhui) {
        return;
    }
    if (_carAround) {
        [_cellArr removeAllObjects];
        [self netRequst];
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)keyboardWillShow:(NSNotification *)notification {
     keyBoradShow = YES;
     NSDictionary *userInfo = [notification userInfo];
    
     NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
     CGRect keyboardRect = [aValue CGRectValue];
    
     [UIView animateWithDuration:0.5 animations:^{
         self.view.frame = CGRectMake(0, - CGRectGetHeight(keyboardRect)  , CGRectGetWidth(self.view.frame),  CGRectGetHeight(self.view.frame));
     }];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    keyBoradShow = NO;
    [UIView animateWithDuration:0.5 animations:^{
        self.view.frame = CGRectMake(0, 0  , CGRectGetWidth(self.view.frame),  CGRectGetHeight(self.view.frame));
    }];
}

- (void)netRequst {
    [self.view makeToastActivity];
    if (!_carAround) {
        _carAround = [CarAroundDataSource dataSourceWithRequestor:self];
    }
    [_carAround getCurrenScore:^(id result) {
        [Common setCurrenVB:@([[result customObjectForkey:@"vb"] integerValue])];
        _scoreCount.text = [result customObjectForkey:@"vb"] ;
    } anfFail:^(id result) {
        
    }];
    
    [_carAround queryOilCardDetail:^(id result) {
         _tableDataSource = [NSMutableArray arrayWithArray:[result customObjectForkey:@"card"]];
        [self initDataSource];
    } anfFail:^(id result) {
        
    }];
    
}


- (void)initDataSource {
    if (_tableDataSource.count <= 0) {
        return;
    }
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView reloadData];
    [self.view hideToastActivity];
}

- (void)initAbout {
    self.title = @"油卡充值";
    if (!_cellArr) {
        _cellArr = [NSMutableArray new];
    }
    _twoBaiBtn.selected = YES;
    _twoBaiSeleteImg.hidden = NO;
    _payScore.text = @"20000";
    [self showNavBarWithRightTitle:nil andRightAction:nil andLeftAction:nil andCustom:NO];
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerNib:[UINib nibWithNibName:@"OilCardTableViewCell" bundle:nil] forCellReuseIdentifier:cellIndentifire];
}


- (void)networkingStartHandleWithRequestIdentifier:(RequestIdentifier)identifier{
    
}

- (void)networkingFailureHandleWithRequestIdentifier:(RequestIdentifier)identifier errorMessage:(NSString *)message{
    [super networkingFailureHandleWithRequestIdentifier:identifier errorMessage:message];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - tableView delegate & dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
   
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  _tableDataSource.count <= 0 ? 0 : _tableDataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    OilCardTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifire forIndexPath:indexPath];
    cell.info = [_tableDataSource objectAtIndex:indexPath.row];
    cell.target = self;
    cell.checkBtn.hidden = NO;
    cell.RechargeBtn.hidden = YES;
    cell.tag = 300 + indexPath.row;
    cell.action = @selector(seleteCell:);
    
    if (_oidNum && _oidNum.length > 0) {
        if ([_oidNum isEqualToString:cell.oilCardLabel.text]) {
            [cell rechargeBtn:cell.checkBtn];
        }
    }
    if (_cellArr.count != _tableDataSource.count) {
        [_cellArr addObject:cell];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 72;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    OilCardTableViewCell *oil = (OilCardTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    [oil rechargeBtn:oil.checkBtn];
}

- (void)seleteCell:(NSDictionary *)info {
    _oilInfo = [info customObjectForkey:@"info"];
    OilCardTableViewCell *oilCard = [info customObjectForkey:@"cell"];
     if (_tableDataSource.count > 1) {
         for (OilCardTableViewCell *cell in _cellArr) {
             if (cell != oilCard) {
                 cell.checkBtn.selected = NO;
             }
         }
     }
}

- (void)setCountScore:(NSString *)countScore{
    _countScore = countScore;
    _payScore.text = [NSString stringWithFormat:@"%ld",[_countScore integerValue] * 100];
}


- (void)textFieldDidBeginEditing:(UITextField *)textField{
  
    _oneThousandSeleteImg.hidden = YES;
    _twoBaiSeleteImg.hidden = YES;
    _oneThousandSeleteImg.hidden = YES;
    _inputSeleteImg.hidden = NO;
    _fourBaiSeleteImg.hidden = YES;
    _oneThousandBtn.selected = NO;
    _fourBaiAction.selected = NO;
    _oneThousandBtn.selected = NO;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    self.countScore = textField.text;
    
}

//限制输入数字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
         //只能输入数字
        NSCharacterSet *cs;
        cs = [[NSCharacterSet characterSetWithCharactersInString:Point]invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
        BOOL canChange = [string isEqualToString:filtered];
        return canChange;
}

- (IBAction)twoBaiAction:(id)sender {
  
    [self judgeKeyBoardShow];
    _fourBaiSeleteImg.hidden = YES;
    _fourBaiAction.selected = NO;
    _oneThousandSeleteImg.hidden = YES;
    _fourBaiAction.selected = NO;
    _inputSeleteImg.hidden = YES;
    _inputText.text = @"";
    
    _twoBaiSeleteImg.hidden = NO;
    _twoBaiBtn.selected = YES;
    
    self.countScore = _twoBaiBtn.titleLabel.text;
}

- (IBAction)fourBaiAction:(id)sender {
    [self judgeKeyBoardShow];
    _twoBaiBtn.selected = NO;
    _twoBaiSeleteImg.hidden = YES;
    _oneThousandBtn.selected = NO;
    _oneThousandSeleteImg.hidden = YES;
    
    _inputSeleteImg.hidden = YES;
    _inputText.text = @"";
    
    _fourBaiAction.selected = YES;
    _fourBaiSeleteImg.hidden = NO;
    
    self.countScore = _fourBaiAction.titleLabel.text;
    
}

- (void)judgeKeyBoardShow {
    [self.view endEditing:YES];
}

- (IBAction)OneThousandAction:(id)sender {
    [self judgeKeyBoardShow];
    _twoBaiBtn.selected = NO;
    _twoBaiSeleteImg.hidden = YES;
    
    _fourBaiAction.selected = NO;
    _fourBaiSeleteImg.hidden = YES;
    
    _inputSeleteImg.hidden = YES;
    _inputText.text = @"";
    
    _oneThousandSeleteImg.hidden = NO;
    _oneThousandBtn.selected = YES;
    
    self.countScore = _oneThousandBtn.titleLabel.text;
}

- (IBAction)payAction:(id)sender {
    [self judgeKeyBoardShow];
    if (!_oilInfo) {
        [self.view makeToast:@"请选择充值油卡" duration:1.5f position:TOP_POINT];
        return;
    }
    if (_payScore.text == 0) {
        [self.view makeToast:@"请输入或者选择充值金额" duration:1.5f position:TOP_POINT];

        return;
    }
    if([_payScore.text integerValue] > [_scoreCount.text integerValue]){
        [self.view makeToast:@"积分不足哦,亲!" duration:1.5f position:TOP_POINT];
        return;
    }
    _carAround.oilCard = [_oilInfo customObjectForkey:@"CARD_NUMBER"];
    _carAround.name = [_oilInfo customObjectForkey:@"CARDHOLDER"];
    _carAround.vb = _payScore.text;
    [_carAround scoreExchangeOilCar:^(id result) {
        [self JoiningTogetherAlertTitle];
    } anfFail:^(id result) {
        
    }];
}

- (void)alertViewCancel:(UIAlertView *)alertView{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)JoiningTogetherAlertTitle {
    NSString *jifen = @"积分";
    //充值多少元
    NSString *price = [[[NSString stringWithFormat:@"%ld",[_payScore.text integerValue] / 100] stringByAppendingString:RMB] stringByAppendingString:@"\n"];
    //消耗积分
    NSString *payScore = [[@"消耗" stringByAppendingString:_payScore.text] stringByAppendingString:@"积分"];
//    _payScore.text
    //剩余积分
    NSString *remaining = [[[[NSString stringWithFormat:@"剩余%ld",([_scoreCount.text integerValue] - [_payScore.text integerValue])] stringByAppendingString:jifen] stringByAppendingString:@"\n"] stringByAppendingString:@"(订单已完成,10分钟后可以充值成功)"];
    NSString *str = [[[@"充值成功,充值" stringByAppendingString:price] stringByAppendingString:[payScore stringByAppendingString:@"\n"]] stringByAppendingString:remaining];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
    [alert show];
    [_carAround getCurrenScore:^(id result) {
        [Common setCurrenVB:@([[result customObjectForkey:@"vb"] integerValue])];
        _scoreCount.text = [result customObjectForkey:@"vb"] ;
    } anfFail:^(id result) {
        
    }];
}

- (IBAction)payAnyAcount:(id)sender {
    OilCardQueryViewController *oil = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"oilQuery"];
    oil.Type = 2;
    oil.target = self;
    oil.action = @selector(addOilAction:);
    [self.navigationController pushViewController:oil animated:YES];
}

- (void)addOilAction:(NSDictionary *)dic {
    [_tableDataSource addObject:dic];
    _cellArr = [NSMutableArray new];
    _oidNum = [dic objectForKey:@"CARD_NUMBER"];
    [_tableView reloadData];
    fanhui = YES;
}

@end
